package com.starry.module.system.core.file.client.local;

import cn.hutool.core.io.FileUtil;
import com.starry.core.common.execption.ServiceException;
import com.starry.module.system.core.file.client.AbstractFileClient;
import com.starry.module.system.core.file.client.domain.UploadSuccessDto;
import com.starry.module.system.core.file.entity.FileConfig;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 本地文件客户端
 *
 * @author xiaoke
 */
public class LocalFileClient extends AbstractFileClient {

    public LocalFileClient(Long id, FileConfig config) {
        super(config);
    }

    @Override
    protected void doInit() {
        // 补全风格。例如说 Linux 是 /，Windows 是 \
        if (!config.getBasePath().endsWith(File.separator)) {
            config.setBasePath(config.getBasePath() + File.separator);
        }
    }

    @Override
    public UploadSuccessDto upload(byte[] content, String originalFilename, String type) throws Exception {
        // 执行写入
        UploadSuccessDto uploadSuccess = getFilePath(originalFilename);
        FileUtil.writeBytes(content, uploadSuccess.getFilePath());
        // 拼接访问路径
        uploadSuccess.setFileUrl(super.formatFileUrl(config.getDomain(), uploadSuccess.getFileName()));
        uploadSuccess.setConfigId(config.getId());

        //去掉filePath中的，basePath
        uploadSuccess.setFilePath(
                uploadSuccess.getFilePath().replace(config.getBasePath(), "")
                        .replaceAll("\\\\", "/")
        );

        return uploadSuccess;
    }

    @Override
    public void delete(String path) throws Exception {
        FileUtil.del(path);
    }

    @Override
    public byte[] getContent(String path) throws Exception {
        return FileUtil.readBytes(formatPath(path));
    }

    private UploadSuccessDto getFilePath(String originalFileName) {
        try {
            // 获取当前日期并以"年-月-日"
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String dateStr = currentDate.format(formatter);
            // 创建以日期命名的目录（如果不存在）
            Path directory = Paths.get(config.getBasePath(), dateStr);
            //获取扩展名
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;
            Files.createDirectories(directory);

            UploadSuccessDto uploadSuccessDto = new UploadSuccessDto();
            uploadSuccessDto.setFileName(fileName);
            uploadSuccessDto.setFilePath(directory + File.separator + fileName);

            return uploadSuccessDto;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("上传文件失败");
        }
    }

    private String formatPath(String path) {
        return config.getBasePath() + path;
    }

}
